<!--
 * @Descripttion: (房屋信息表/lay_house)
 * @Author: (admin)
 * @Date: (2024-09-28)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="商家" prop="companyId">
        <el-select clearable v-model="queryParams.companyId" placeholder="请选择商家id">
          <el-option v-for="item in options.sql_company " :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue">
            <span class="fl">{{ item.dictLabel }}</span>
            <span class="fr" style="color: var(--el-text-color-secondary);">{{ item.dictValue }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房屋标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入房屋标题" />
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['layhouse:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :disabled="single" v-hasPermi="['layhouse:edit']" plain icon="edit"
          @click="handleUpdate">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['layhouse:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['layhouse:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="title" label="房屋标题" width="300" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="name" label="房屋描述" align="center" :show-overflow-tooltip="true" />

      <!-- <el-table-column prop="videoUrl" label="视频url" align="center" v-if="columns.showColumn('videoUrl')">
        <template #default="scope">
          <ImagePreview :src="scope.row.videoUrl"></ImagePreview>
        </template>
</el-table-column> -->
      <el-table-column prop="tags" label="标签" align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('remark')"/> -->
      <el-table-column prop="address" label="地址" align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column prop="id" label="Id" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('id')"/> -->
      <el-table-column prop="lon" label="经度" align="center" />
      <el-table-column prop="lat" label="纬度" align="center" />
      <el-table-column prop="contact" label="联系人" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="tel" label="联系电话" align="center" :show-overflow-tooltip="true" />

      <el-table-column prop="mainImageUrl" label="图片" align="center">
        <template #default="scope">
          <ImagePreview :src="scope.row.mainImageUrl"></ImagePreview>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="icon" label="图标" align="center" v-if="columns.showColumn('icon')">
        <template #default="scope">
          <ImagePreview :src="scope.row.icon"></ImagePreview>
        </template>
      </el-table-column> -->
      <el-table-column prop="companyName" label="商家" align="center">
        <!-- <template #default="scope">
          <dict-tag :options=" options.sql_company " :value="scope.row.companyId"  />
        </template> -->
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <dict-tag :options="options.status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['layhouse:edit']"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['layhouse:delete']"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />


    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">

        <el-tabs type="border-card">
          <el-tab-pane label="基础信息">
            <el-row :gutter="20">
              <!-- <el-col :lg="12">
            <el-form-item label="商家" prop="companyId">
              <el-select v-model="form.companyId"  placeholder="请选择商家id">
                <el-option
                  v-for="item in options.sql_company" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->


              <el-col :lg="16">
                <el-form-item label="房屋标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入房屋标题" />
                </el-form-item>
              </el-col>

              <el-col :lg="8">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status">
                    <el-option v-for="item in options.status" :key="item.dictValue" :value="item.dictValue"
                      :label="item.dictLabel">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="24">
                <el-form-item label="房屋描述" prop="name">
                  <el-input v-model="form.name" placeholder="请输入房屋描述" />
                </el-form-item>
              </el-col>
              <el-col :lg="24">
                <el-form-item label="标签" prop="tags">
                  <el-input v-model="form.tags" placeholder="请输入标签" />
                </el-form-item>
              </el-col>
              <el-col :lg="12">
                <el-form-item label="介绍" prop="info">
                  <el-input v-model="form.info" maxlength="200" type="textarea" placeholder="请输入介绍" />
                </el-form-item>
              </el-col>

              <el-col :lg="12">
                <el-form-item label="简介" prop="content">
                  <el-input v-model="form.content" type="textarea" maxlength="200" placeholder="请输入简介" />
                </el-form-item>
              </el-col>
              <el-col :lg="12">
                <el-form-item label="纬度" prop="lat">
                  <el-input v-model="form.lat" placeholder="请输入坐标" />
                </el-form-item>
              </el-col>
              <el-col :lg="12">
                <el-form-item label="经度" prop="lon">
                  <el-input v-model="form.lon" placeholder="请输入坐标" />
                </el-form-item>
              </el-col>
              <el-col :lg="24">
                <el-form-item label="主图" prop="mainImageUrl">
                  <UploadImage v-model="form.mainImageUrl" :data="{ uploadType: 1 }" />
                </el-form-item>
              </el-col>
              <el-col :lg="12">
                <el-form-item label="联系人" prop="contact">
                  <el-input v-model="form.contact" placeholder="请输入联系人" />
                </el-form-item>
              </el-col>
              <el-col :lg="12">
                <el-form-item label="联系电话" prop="tel">
                  <el-input v-model="form.tel" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>

              <el-col :lg="24">
                <el-form-item label="地址" prop="address">
                  <el-input v-model="form.address" placeholder="请输入地址" />
                </el-form-item>
              </el-col>
              <el-col :lg="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-col>

              <!-- <el-col :lg="8">
            <el-form-item label="视频" prop="videoUrl">
              <UploadImage v-model="form.videoUrl" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col> -->



              <!-- <el-col :lg="8">
            <el-form-item label="图标" prop="icon">
              <UploadImage v-model="form.icon" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col> -->






            </el-row>
          </el-tab-pane>
          <el-tab-pane label="详情图">
            <el-col :lg="24">
              <!-- <el-form-item label="详情图" prop="imageUrl"> -->
              <UploadImage v-model="form.imageUrl" :limit="5" :data="{ uploadType: 1 }" />
              <!-- </el-form-item> -->
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="属性信息">

            <!-- <el-form-item label="菜单权限"> -->
            <!-- <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
            <!-- :filter-node-method="menuFilterNode" -->

            <el-tree class="tree-border" :data="menuOptions" default-expand-all show-checkbox ref="menuRef"
              node-key="id" empty-text="加载中，请稍后" highlight-current :props="{ children: 'children', label: 'name' }">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span class="fl" :title="data.label">{{ node.label }}</span>
                </div>
              </template>
            </el-tree>

            <!-- </el-form-item> -->
          </el-tab-pane>
          <el-tab-pane label="政策信息">
            <el-tree class="tree-border" :data="PolicyOptions" default-expand-all show-checkbox ref="PolicyRef"
              node-key="id" empty-text="加载中，请稍后" highlight-current :props="{ children: 'children', label: 'name' }">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span class="fl" :title="data.label">{{ node.label }}</span>
                </div>
              </template>
            </el-tree>
          </el-tab-pane>
        </el-tabs>


      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="layhouse">
import {
  listLayHouse,
  addLayHouse, delLayHouse,
  updateLayHouse, getLayHouse,
}
  from '@/api/business/layhouse.js'

import { treelistLayPosition } from '@/api/business/layposition.js'
import { treelistLayPolicy } from '@/api/business/laypolicy'
import tab from '@/plugins/tab';
import { status } from 'nprogress';
import { first } from 'xe-utils';
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'a.CreateTime',
  sortType: 'desc',
  companyId: undefined,
  title: undefined,
})
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'lat', label: '坐标' },
  { visible: true, align: 'center', type: 'dict', prop: 'statusName', label: '状态名称', showOverflowTooltip: true, dictType: 'status' },
  { visible: true, align: 'center', type: 'dict', prop: 'status', label: '状态', showOverflowTooltip: true, dictType: 'status' },
  { visible: true, align: 'center', type: 'img', prop: 'videoUrl', label: '视频url', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'tags', label: '标签', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'remark', label: '备注', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'address', label: '地址', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'id', label: 'Id', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'lon', label: '坐标' },
  { visible: false, align: 'center', type: '', prop: 'tel', label: '联系电话', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'contact', label: '联系人', showOverflowTooltip: true },
  { visible: false, align: 'center', type: 'img', prop: 'imageUrl', label: '图片url', showOverflowTooltip: true },
  { visible: false, align: 'center', type: 'img', prop: 'icon', label: '图标', showOverflowTooltip: true },
  { visible: false, align: 'center', type: 'dict', prop: 'companyId', label: '商家id', showOverflowTooltip: true, dictType: 'sql_company' },
  { visible: false, align: 'center', type: '', prop: 'info', label: '介绍', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'content', label: '简介', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'title', label: '房屋标题', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'name', label: '房屋描述', showOverflowTooltip: true },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])

const queryRef = ref()
const menuRef = ref()
const menuOptions = ref([])
const PolicyRef = ref()
const PolicyOptions = ref([])
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
  "status",
  // "sql_company",
]

proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.dictType] = element.list
  })
})


//民宿获取位置信息
const PostionParams = reactive({
  status: '1'

})
treelistLayPosition(PostionParams).then(res => {
  const { code, data } = res
  if (code == 200) {
    menuOptions.value = data
    console.log(data)
  }
})
//民宿获取位置信息
const PolicyParams = reactive({
  status: '1'

})
treelistLayPolicy(PolicyParams).then(res => {
  const { code, data } = res
  if (code == 200) {
    PolicyOptions.value = data
    console.log(data)
  }
})
function getList() {
  loading.value = true
  listLayHouse(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}



// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1
  multiple.value = !selection.length;
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({

  single: true,
  multiple: true,
  form: {},
  rules: {
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    name: [{ required: true, message: "房屋描述不能为空", trigger: "blur" }],
    // companyId: [{ required: true, message: "商家不能为空", trigger: "blur" }],
    lon: [{ required: true, message: "经度不能为空", trigger: "blur" }],
    lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
  },
  options: {
    // 状态名称 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    status: [],
    // 商家id 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    sql_company: [],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  if (proxy.$refs.menuRef != undefined) {
    proxy.$refs.menuRef.setCheckedKeys([])
  };
  if (proxy.$refs.PolicyRef != undefined) {
    proxy.$refs.PolicyRef.setCheckedKeys([])
  };
  (form.value = {
    lat: null,
    statusName: null,
    status: null,
    updateBy: null,
    updateTime: null,
    createBy: null,
    createTime: null,
    videoUrl: null,
    tags: null,
    remark: null,
    address: null,
    id: null,
    lon: null,
    tel: null,
    contact: null,
    imageUrl: null,
    mainImageUrl: null,
    icon: null,
    companyId: null,
    info: null,
    content: null,
    title: null,
    name: null,
    positionIds: [],
    policyIds: [],
    menuCheckStrictly: true,
  });
  proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = '添加房屋信息表'
  opertype.value = 1
  form.value.status = '1'
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getLayHouse(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改房屋信息表'
      opertype.value = 2
      form.value = {
        ...data,
      }
      console.log(data)
      data.layHousePositionNav.forEach((v) => {
        nextTick(() => {
          proxy.$refs.menuRef.setChecked(v.positionId, true, false)
        })
      })
      //layHousePolicyNav
      data.layHousePolicyNav.forEach((v) => {
        nextTick(() => {
          proxy.$refs.PolicyRef.setChecked(v.policyId, true, false)
        })
      })
    }
  })
}
// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  const checkedKeys = proxy.$refs.menuRef.getCheckedKeys()
  // 半选中的菜单节点
  const halfCheckedKeys = proxy.$refs.menuRef.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  console.log("getMenuAllCheckedKeys", checkedKeys);
  return checkedKeys
}
function getPolicyAllCheckedKeys() {
  // 目前被选中的菜单节点
  const _checkedKeys = proxy.$refs.PolicyRef.getCheckedKeys()
  // 半选中的菜单节点
  const _halfCheckedKeys = proxy.$refs.PolicyRef.getHalfCheckedKeys()
  _checkedKeys.unshift.apply(_checkedKeys, _halfCheckedKeys)
  console.log("getPolicyAllCheckedKeys", _checkedKeys);
  return _checkedKeys
}
// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      form.value.positionIds = getMenuAllCheckedKeys();
      form.value.policyIds = getPolicyAllCheckedKeys();
      if (form.value.id != undefined && opertype.value === 2) {
        updateLayHouse(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLayHouse(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delLayHouse(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}



// 导出按钮操作
function handleExport() {
  proxy
    .$confirm("是否确认导出房屋信息表数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      await proxy.downFile('/business/LayHouse/export', { ...queryParams })
    })
}

handleQuery()

function customNodeClass(data, node) {
  if (data.level == 1) {
    return 'tree-item-flex'
  }
  return null
}
</script>

<style>
/* tree border */
.tree-border {
  margin-top: 5px;
  /* border: 1px solid #e5e6e7; */
  background: var(--base-bg-main) none;
  border-radius: 4px;
  width: 100%;
  /* height: 400px; */
  overflow-y: auto;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.el-dropdown {
  vertical-align: middle;
}


/* 控制树形节点横向显示 */
.el-tree-node.is-expanded>.el-tree-node__children {
  display: flex !important;
  flex-wrap: wrap !important;
  /* flex横向布局换行显示 */
}

/* 去除点击收缩图标时：横向显示的数据会先晃动成纵向显示的再收缩的现象*/
.collapse-transition {
  transition: none !important;
}

.el-tree-node__content>.el-tree-node__expand-icon {
  box-sizing: border-box !important;
  display: none !important;
}
</style>